//
//  AppDelegate+Network.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/8/8.
//

import Foundation

#if DEBUG
//    import LLDebugTool
#endif

extension AppDelegate {
    func configNetwork() {
        setupEnvironment()
        setupNetworkLog()
    }

    private func setupEnvironment() {
        #if DEBUG
            // 启动调试
//            LLDebugTool.shared().startWorking()
            if let typeNum: Int = WmcUserdefault.object(forKey: .networkEnvironment),
               let typeEnum = YPWmcManager.EnvironmentType(rawValue: typeNum)
            {
                YPWmcManager.switchNetworkEnvironment(typeEnum)
            } else {
                YPWmcManager.switchNetworkEnvironment(.test)
            }
        #else
            YPWmcManager.switchNetworkEnvironment(.release)
        #endif
    }

    private func setupNetworkLog() {
        #if DEBUG
//            if let isOpenCache: Bool = WmcUserdefault.object(forKey: .networkLogSwitch) {
//                setNetworkLog(isOpenCache)
//            } else {
//                setNetworkLog(false)
//            }
        setNetworkLog(true)
        #else
            setNetworkLog(false)
        #endif
//        setNetworkLog(true)
    }

    private func setNetworkLog(_ isOpen: Bool = false) {
        YPNetworkManager.shared.isEnabelLog = isOpen

        if let isOpenCache: Bool = WmcUserdefault.object(forKey: .networkLogSwitch) {
            if isOpenCache != isOpen {
                WmcUserdefault.save(value: isOpen, forKey: .networkLogSwitch)
            }
        } else {
            WmcUserdefault.save(value: isOpen, forKey: .networkLogSwitch)
        }
    }
}

#if DEBUG
extension UIWindow {
     open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        if motion == .motionShake {
            YPDevice.PlayShake(.heavy)
            
            let alertController = UIAlertController(title: "调试工具", message: "", preferredStyle: .actionSheet)
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            let switchNetAction = UIAlertAction(title: "网络环境", style: .default) { _ in
                let vc = WmcDevEnvironmentVC()
                YPApp.CurrentVC?.navigationController?.present(vc, animated: true)
            }
//            let apiTestAction = UIAlertAction(title: "测试接口", style: .default) { _ in
//
//            }
            alertController.addAction(cancelAction)
            alertController.addAction(switchNetAction)
//            alertController.addAction(apiTestAction)
            YPApp.CurrentVC?.navigationController?.present(alertController, animated: true, completion: nil)
        }
     }
}
#endif
